package com.ellricky.newtv.adapter

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ellricky.newtv.NewTvConnectActivity
import com.ellricky.newtv.NewTvCourseFileActivity
import com.ellricky.newtv.R
import com.ellricky.newtv.bean.TvCourseType
import com.ellricky.newtv.const.TvConst

class CourseTypePagerAdapter :
    RecyclerView.Adapter<CourseTypePagerAdapter.CourseTypePagerHolder>() {

    private var courseTypeList: List<List<TvCourseType>>? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CourseTypePagerHolder {
        return CourseTypePagerHolder(
            LayoutInflater.from(parent.context)
                .inflate(R.layout.item_course_type_pager, parent, false)
        )
    }

    override fun onBindViewHolder(holder: CourseTypePagerHolder, position: Int) {
        holder.bindData(courseTypeList?.get(position))
    }

    override fun getItemCount(): Int {
        return courseTypeList?.size ?: 0
    }

    fun setCourseTypeList(list: List<List<TvCourseType>>) {
        this.courseTypeList = list
        this.notifyDataSetChanged()
    }

    class CourseTypePagerHolder(val view: View) : RecyclerView.ViewHolder(view) {
        private val rvCourseType: RecyclerView = view.findViewById(R.id.rv_course_type)

        fun bindData(list: List<TvCourseType>?) {
            if (list.isNullOrEmpty()) {
                return
            }
            val context = view.context
            val adapter = CourseTypeAdapter().apply {
                setList(list)
            }
            rvCourseType.adapter = adapter
            rvCourseType.layoutManager = GridLayoutManager(context, 2)
            adapter.setOnItemClickListener { _,
                                             _,
                                             position ->
                val data = adapter.data[position]
                if (data.endState == 2) {
                    context.startActivity(Intent(context, NewTvConnectActivity::class.java))
                    Toast.makeText(context, "请联系管理员进行操作", Toast.LENGTH_SHORT).show()
                } else {
                    context.startActivity(
                        Intent(
                            context,
                            NewTvCourseFileActivity::class.java
                        ).apply {
                            putExtra(TvConst.KEY_ID, data.course_id)
                        })
                }
            }
        }
    }
}